package com.xjy.rpc.netty.handler;
/**
 * @description: 消息解码handler
 * @author XJY
 * @date 2024/10/21 9:10
 * @version 1.0
 */
import com.alibaba.fastjson.JSON;
import com.xjy.rpc.config.Constant;
import com.xjy.rpc.netty.message.AbstractMessageBody;
import com.xjy.rpc.netty.message.RpcRequest;
import com.xjy.rpc.netty.message.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf,
                          List<Object> list) throws Exception {
        //读取消息
        short magic = byteBuf.readShort();
        short messageType = byteBuf.readShort();
        long requestId = byteBuf.readLong();

        int msgLength = byteBuf.readInt();
        byte[] bytes = new byte[msgLength];
        //TODO 默认buf一次传输容量只有2048 可能会小于msgLength，这里需要读完整个msg
        //bytebuf 提供读指针和写指针 ridx widx 和总容量cap
        //如果可读字节数小于消息长度，直接返回
        if (byteBuf.readableBytes() < bytes.length){
            byteBuf.resetReaderIndex();
            return;
        }
        byteBuf.readBytes(bytes);
        AbstractMessageBody o = null;
        if (messageType == Constant.MESSAGE_TYPE_REQ){
             o = JSON.parseObject(bytes, RpcRequest.class);
        } else if (messageType == Constant.MESSAGE_TYPE_RES) {
            o = JSON.parseObject(bytes, RpcResponse.class);
        }
        list.add(o);

    }
}
